<template>
  <div class="address-management-container">
    <!-- 头部操作区 -->
    <div class="header-actions">
      <el-button type="primary" @click="openDialog('add')" class="add-button">
        <el-icon class="mr-1">
          <Plus/>
        </el-icon>
        添加新地址
      </el-button>
    </div>

    <!-- 地址列表 -->
    <div v-loading="loading" class="address-list-wrapper">
      <transition-group name="list" tag="div" class="address-list">
        <!-- 地址卡片 -->
        <div
            v-for="address in addresses"
            :key="address.addressId"
            class="address-card"
            :class="{ 'default-card': address.isDefault }"
        >
          <div class="card-header">
            <div class="badge-wrapper">
              <el-tag
                  v-if="address.isDefault"
                  type="danger"
                  size="small"
                  effect="dark"
              >
                默认地址
              </el-tag>
            </div>
            <div class="user-info">
              <span class="userName">收货人名字:{{ address.userName }}</span>
              <span class="phone">手机号:{{ address.phoneNumber }}</span>
            </div>
          </div>

          <div class="card-body">
            <div class="address-detail">
              <el-icon class="location-icon">
                <Location/>
              </el-icon>
              <span class="detail-text">详细地址与门牌号：{{ address.addressDetail }}</span>
            </div>
          </div>

          <div class="card-actions">
            <el-tooltip content="设为默认" placement="top" v-if="!address.isDefault">
              <el-button
                  type="success"
                  size="small"
                  circle
                  plain
                  @click="setDefaultAddress(address.addressId)"
              >
                <el-icon>
                  <Star/>
                </el-icon>
              </el-button>
            </el-tooltip>

            <el-tooltip content="编辑" placement="top">
              <el-button
                  type="primary"
                  size="small"
                  circle
                  plain
                  @click="openDialog('edit', address)"
              >
                <el-icon>
                  <Edit/>
                </el-icon>
              </el-button>
            </el-tooltip>

            <el-popconfirm
                title="确认删除该地址吗？"
                confirm-button-text="确定"
                cancel-button-text="取消"
                @confirm="deleteAddress(address.addressId)"
            >
              <template #reference>
                <el-tooltip content="删除" placement="top">
                  <el-button
                      type="danger"
                      size="small"
                      circle
                      plain
                  >
                    <el-icon>
                      <Delete/>
                    </el-icon>
                  </el-button>
                </el-tooltip>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </transition-group>

      <div v-if="addresses.length === 0" class="empty-state">
        <el-empty description="暂无地址信息，点击上方按钮添加地址"/>
      </div>
    </div>

    <!-- 地址编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="800px"
        :close-on-click-modal="false"
        destroy-on-close
    >
      <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-position="top"
          status-icon
      >
        <el-row :gutter="24">
          <!-- 左侧表单 -->
          <el-col :span="12">
            <el-form-item label="收件人姓名" prop="userName">
              <el-input
                  v-model="formData.userName"
                  placeholder="请输入收件人姓名"
                  clearable
              />
            </el-form-item>

            <el-form-item label="联系电话" prop="phoneNumber">
              <el-input
                  v-model="formData.phoneNumber"
                  placeholder="请输入11位手机号"
                  maxlength="11"
                  clearable
              />
            </el-form-item>

            <el-form-item label="设为默认地址">
              <el-switch
                  v-model="formData.is_default"
                  :active-value="1"
                  :inactive-value="0"
                  active-text="默认地址"
                  inactive-text="普通地址"
              />
            </el-form-item>
          </el-col>

          <!-- 右侧地图 -->
          <el-col :span="12">
            <el-form-item label="选择位置" prop="addressDetail">
              <el-input
                  v-model="formData.addressDetail"
                  placeholder="点击地图选择位置"
                  readonly
                  @click="showMap = true"
              />

              <div class="map-container" v-show="showMap">
                <MapComponent
                    :key="mapKey"
                    :initialPosition="initialMapPosition"
                    @locationSelected="handleMapSelect"
                    class="map-wrapper"
                />
              </div>

              <div class="coordinates-preview">
                <div class="coordinate-preview-item">
                  <span class="label">经度:</span>
                  <el-tag size="small">{{ formData.longitude || '--' }}</el-tag>
                </div>
                <div class="coordinate-preview-item">
                  <span class="label">纬度:</span>
                  <el-tag size="small">{{ formData.latitude || '--' }}</el-tag>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
            type="primary"
            @click="submitForm"
            :loading="submitting"
        >
          {{ dialogType === 'add' ? '确认添加' : '保存修改' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {ElMessage} from 'element-plus'
import {Delete, Edit, Location, Plus, Star} from '@element-plus/icons-vue'
import {useUserStore} from '/src/store/user.js'
import {
  addNewAddress,
  fetchAddressList,
  removeAddress,
  setDefaultAddress as apiSetDefault,
  updateExistingAddress
} from '../store/address'
import MapComponent from '../components/MapComponent.vue'

// 状态管理
const userStore = useUserStore()
const addresses = ref([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref('add')
const showMap = ref(false)
const mapKey = ref(0)
const submitting = ref(false)
const formRef = ref(null)

// 表单数据
const formData = ref({
  addressId: null,
  userId: null,
  userName: '',
  phoneNumber: '',
  addressDetail: '',
  latitude: null,
  longitude: null,
  is_default: 0
})

// 计算属性
const dialogTitle = computed(() =>
    dialogType.value === 'add' ? '新增收货地址' : '编辑收货地址'
)

const initialMapPosition = computed(() => {
  if (formData.value.latitude && formData.value.longitude) {
    return [formData.value.latitude, formData.value.longitude]
  }
  return null
})

// 生命周期钩子
onMounted(async () => {
  await userStore.loadUserInfo()
  await loadAddresses()
})

// 地址加载
// 修改 loadAddresses 方法
const loadAddresses = async () => {
  loading.value = true
  try {
    // 关键修改点：直接使用转换后的数据
    addresses.value = await fetchAddressList()
    // 调试用日志
    console.log('Loaded addresses:', addresses.value)
  } catch (error) {
    ElMessage.error({message: '地址加载失败: ', duration: 1000 + error.message})
  } finally {
    loading.value = false
  }
}

// 对话框操作
const openDialog = (type, data) => {
  dialogType.value = type
  if (type === 'edit') {
    formData.value = {
      ...data,
      is_default: data.is_default ? 1 : 0
    }
    showMap.value = true
  } else {
    formData.value = {
      addressId: null,
      userId: userStore.userId, // 确保 userId 被正确使用
      userName: userStore.userName,
      phoneNumber: userStore.phoneNumber,
      addressDetail: '',
      latitude: null,
      longitude: null,
      is_default: 0
    }
  }
  dialogVisible.value = true
  mapKey.value++ // 强制刷新地图组件
}

// 表单提交
const submitForm = async () => {
  submitting.value = true
  try {
    await formRef.value.validate()

    // 构造请求数据
    const payload = {
      ...formData.value,
      latitude: formatCoordinateForSubmit(formData.value.latitude),
      longitude: formatCoordinateForSubmit(formData.value.longitude)
    }

    // API调用
    if (dialogType.value === 'add') {
      await addNewAddress(payload)
    } else {
      await updateExistingAddress(payload.addressId, payload)
    }

    // 处理默认地址
    if (payload.is_default === 1) {
      await apiSetDefault(payload.addressId)
    }

    ElMessage.success(dialogType.value === 'add' ? '地址添加成功' : '地址更新成功')
    dialogVisible.value = false
    await loadAddresses()
  } catch (error) {
    handleFormError(error)
  } finally {
    submitting.value = false
  }
}

// 地址删除
const deleteAddress = async (id) => {
  try {
    await removeAddress(id)
    await loadAddresses()
    ElMessage.success('地址删除成功')
  } catch (error) {
    ElMessage.error('删除失败: ' + error.message)
  }
}

// 设置默认地址
const setDefaultAddress = async (id) => {
  try {
    await apiSetDefault(id)
    await loadAddresses()
    ElMessage.success('默认地址设置成功')
  } catch (error) {
    ElMessage.error('设置失败: ' + error.message)
  }
}

// 地图交互处理
const handleMapSelect = ({latitude, longitude, address}) => {
  formData.value.latitude = latitude
  formData.value.longitude = longitude
  formData.value.addressDetail = address
  showMap.value = false
}

// 工具函数
const formatCoordinate = (value) => {
  const num = Number(value)
  return isNaN(num) ? '--' : num.toFixed(6)
}

const formatCoordinateForSubmit = (value) => {
  const num = Number(value)
  return isNaN(num) ? '' : num.toFixed(6)
}

// 错误处理
const handleFormError = (error) => {
  const errorMessages = {
    400: '请求参数错误',
    401: '登录状态已过期',
    403: '权限不足',
    500: '服务器错误'
  }

  ElMessage.error({
    message: error.response?.data?.message ||
        errorMessages[error.response?.status] ||
        error.message || '操作失败',
    duration: 3000
  })
}

// 表单验证规则
const formRules = {
  userName: [
    {required: true, message: '请输入收件人姓名', trigger: 'blur'},
    {min: 2, max: 10, message: '姓名长度2-10个字符', trigger: 'blur'}
  ],
  phoneNumber: [
    {required: true, message: '请输入联系电话', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur'}
  ],
  addressDetail: [
    {required: true, message: '请选择或输入详细地址', trigger: 'change'}
  ],
  latitude: [
    {required: true, message: '请通过地图选择位置', trigger: 'change'},
    {
      validator: (_, value, callback) => {
        const num = Number(value)
        if (isNaN(num)) return callback(new Error('无效的纬度值'))
        if (num < -90 || num > 90) return callback(new Error('纬度范围(-90 ~ 90)'))
        callback()
      },
      trigger: 'change'
    }
  ],
  longitude: [
    {required: true, message: '请通过地图选择位置', trigger: 'change'},
    {
      validator: (_, value, callback) => {
        const num = Number(value)
        if (isNaN(num)) return callback(new Error('无效的经度值'))
        if (num < -180 || num > 180) return callback(new Error('经度范围(-180 ~ 180)'))
        callback()
      },
      trigger: 'change'
    }
  ]
}
</script>

<style scoped>
.address-management-container {
  width: 1200px;
  margin: 0 auto;
  height: 100%;
  padding: 24px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease-in-out;
}

.el-button {
  margin-bottom: 24px;
}

.addresses-list {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.address-card {
  background-color: #f9fafb;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.address-card ul {
  list-style-type: none;
  padding: 0;
  margin: 0;
}

.address-card li {
  font-size: 16px;
  color: #606266;
  margin-bottom: 12px;
}

.button-group {
  display: flex;
  gap: 12px;
}

.address-form {
  margin-top: 24px;
  padding: 24px;
  background: #f9fafb;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.address-form h3 {
  margin-bottom: 24px;
  font-size: 20px;
  color: #303133;
}

.map-component {
  margin-top: 24px;
}

</style>



